package com.bruce.spring.http.service.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.FileReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Base64;

/**
 * Created by bruce in 2025/6/29 19:30
 */
@RestController
public class SseController {

    private static final Logger log = LoggerFactory.getLogger(SseController.class);

    SseEmitter sseEmitter;

    @RequestMapping("/sse")
    public SseEmitter sseEmitter(String appName, String flowRuleMd5) {
        sseEmitter = new SseEmitter();
        sseEmitter.onCompletion(() -> {
            log.info("SseEmitter 完成: {}, this:{}", appName, this);
        });

        // sseEmitter.onTimeout(() -> {
        //     //
        //     log.info("SseEmitter 超时: {}", appName);
        // });
        //
        // sseEmitter.onError(throwable -> {
        //     //
        //     log.error("SseEmitter 触发异常: {}", appName, throwable);
        // });


        log.info("SseEmitter 连接成功: {}", appName);
        return sseEmitter;
    }

    @RequestMapping("/sse-push")
    public String sendData(String appName) {
        try {
            sseEmitter.send(SseEmitter.event().name(LocalDateTime.now().toString()).data("你好").id("aa").comment("哈哈哈"));

        } catch (IOException e) {
            log.error("SseEmitter 发送异常: {}", appName, e);
        }
        return "发送成功";
    }

}
